// src/composables/useStationData.js

import {ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import axios from 'axios';

export function useStationData() {
    // 列表相关
    const stations = ref([]);
    const selectedStations = ref([]);
    const page = ref(1);
    const size = ref(5);
    const total = ref(0);
    const loading = ref(false);

    // 筛选条件
    const stationName = ref('');
    const address = ref('');
    const status = ref('');

    console.log('Initial page:', page); // 检查初始化时是否为 ref 对象
    console.log('Page in setup:', page, typeof page); // 检查 setup 函数中的 page 是否为 ref 对象

    // 1) 获取站点列表
    const fetchData = () => {
        if (loading.value) return;
        loading.value = true;

        console.log(`Fetching: page=${page.value}, size=${size.value}`);
        const params = { page: page.value, size: size.value };
        if (stationName.value) params.stationName = stationName.value.trim();
        if (status.value && status.value !== '全部') params.status = status.value.trim();
        if (address.value) params.address = address.value.trim();

        axios
            .get('/station/getStationByPage', { params })
            .then((response) => {
                const result = response.data;
                stations.value = result.records || [];
                total.value = result.total || 0;

                // 动态计算最大页数
                const maxPage = Math.ceil(total.value / size.value) || 1;
                if (page.value > maxPage) {
                    console.log(`Page ${page.value} exceeds maxPage ${maxPage}. Resetting to ${maxPage}`);
                    page.value = maxPage;
                    fetchData(); // 重新获取数据
                }
            })
            .catch(() => {
                ElMessage.error('数据加载失败');
                stations.value = [];
            })
            .finally(() => {
                loading.value = false;
            });
    };


    // 2) 处理表格的多选
    const handleSelectionChange = (selection) => {
        selectedStations.value = selection;
    };

    // 3) 删除站点
    const deleteStation = (row, callback) => {
        ElMessageBox.confirm('确认删除该站点吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(() => {
                axios
                    .delete('/station/deleteStation', {params: {id: row.id}})
                    .then(() => {
                        ElMessage.success('删除成功');
                        callback && callback(); // 删除成功后刷新页面
                    })
                    .catch(() => {
                        ElMessage.error('删除失败');
                    });
            })
            .catch(() => {
                ElMessage.info('已取消操作');
            });
    };

    // 4) 上线/下线
    const toggleStationStatus = (row, callback) => {
        const isOffline = row.status === '正常';
        const action = isOffline ? '下线' : '上线';
        const url = isOffline
            ? `/station/offlineStation/${row.id}`
            : `/station/onlineStation/${row.id}`;

        ElMessageBox.confirm(`确认${action}该站点吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(() => {
                axios
                    .put(url)
                    .then(() => {
                        ElMessage.success(`${action}成功`);
                        callback && callback();
                    })
                    .catch(() => {
                        ElMessage.error(`${action}失败`);
                    });
            })
            .catch(() => {
                ElMessage.info('已取消操作');
            });
    };

    // 5) 批量删除
    const batchDelete = (callback) => {
        if (selectedStations.value.length === 0) {
            ElMessage.warning('请先选择站点');
            return;
        }
        const ids = selectedStations.value.map((s) => s.id);
        axios
            .post('/station/batchDelete', ids)
            .then(() => {
                ElMessage.success('批量删除成功');
                callback && callback();
            })
            .catch(() => {
                ElMessage.error('批量删除失败');
            });
    };

    return {
        stations,
        selectedStations,
        page,
        size,
        total,
        loading,
        stationName,
        address,
        status,

        fetchData,
        handleSelectionChange,
        deleteStation,
        toggleStationStatus,
        batchDelete,
    };
}
